/**
* @Description: WoShop商城
* @Author: 梧桐
* @Copyright: 武汉一一零七科技有限公司©版权所有
* @Link: www.s1107.com
* @Contact: QQ:2487937004
*/
<template>
	<view class="uni-column chat">
		<view class="header">
			<view class="" style="display: flex;align-items: center;">
				<image src="@/static/zuo.png" mode="" style="width: 45upx;height: 45upx;" @click="back"></image>
				<text style="font-size: 36upx;margin-left: 30upx;color: #333;">{{name}}</text>
			</view>
			<image src="@/static/gengduo.png" mode="" style="width: 46upx;height: 14upx;padding-right: 20upx;"
				@click="caozuo"></image>
		</view>
		<div v-if="pageShow" style="padding-top: 100upx;">
			<view class="content" id="content" @click="hideKeyboard">
				<div id="scrollview">
					<div class="loading no-more" v-show="!isMore">没有更多了</div>
					<message-show v-for="(item, index) in msgList" :key="index" :avatar="avatar" :id="index"
						:message="item"></message-show>
					<view id="bottom"></view>
				</div>
			</view>
			<Emoji @updata-val="updataVal" @on-upload="onUpload" :input-value='inputValue' :isShow="showEoji"
				@send-message="getInputMessage" v-if="showEoji" @show-emoji="onShowEmoji"></Emoji>
			<view class="chat-footer">
				<chat-input :focus="focus" :input-value="inputValue" :isShow="showEoji" @send-message="getInputMessage"
					@updata-val="updataVal" @on-upload="onUpload" @show-emoji="onShowEmoji"></chat-input>
			</view>
		</div>
		<uni-popup @maskClick="close" ref="caozuo" type="bottom">
			<view class="bot">
				<view class="lista">
					选择操作
				</view>
				<view class="listd" @click="totousu">
					举报
				</view>
				<view class="listd" @click="lahei()">
					拉黑
				</view>
				<view class="quxiao" @click="closed()">
					取消
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import chatInput from '../../components/im-chat/chatinput.vue'
	import messageShow from '../../components/im-chat/messageshow.vue'
	import Emoji from '../../components/im-chat/Emoji.vue'


	export default {
		data() {
			return {
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 110,
					mitemHeight: 0,
				},
				isAnimation: false,
				scrollTop: 0,
				showEoji: false,
				focus: false,
				inputValue: '',
				pageShow: false,
				msgList: [],
				avatar: '',
				toId: '',
				toUserId: '',
				page: 1,
				isMore: true,
				isGetMore: false,
				name: "",
				userid: '',
				formid: '',
				to_uid: '',
				islah: true
			}
		},

		components: {
			chatInput,
			messageShow,
			Emoji
		},

		onLoad(option) {
			this.$loading()
			this.name = option.name
			this.toId = option.toId
			// this. formid = option.formid
			this.userid = option.userId
			this.to_uid = option.to_uid
			const userInfo = JSON.parse(uni.getStorageSync('userInfo'))
			this.avatar = userInfo.headimgurl ? userInfo.headimgurl : this.STATICURL + `images/logo.png`;
			this.toUserId = this.toId
			const res = uni.getSystemInfoSync();
			this.style.pageHeight = res.windowHeight;
			this.style.contentViewHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (100); //像素
			this.getchatlist()

			uni.sendSocketMessage({
				data: JSON.stringify({
					type: 'readmsg',
					data: {
						fromid: uni.getStorageSync('token'),
						toid: this.toId,
					}
				})
			})

			uni.sendSocketMessage({
				data: JSON.stringify({
					type: 'history',
					data: {
						fromid: uni.getStorageSync('token'),
						toid: this.toId,
					}
				})
			})

			uni.onSocketMessage(res => {
				console.log('aaaaaa')
				console.log(res);
				console.log('bbbbbb')
				const data = JSON.parse(res.data)
				if (data.type === 'say') {
					let receiveMsg = data
					console.log(data)
					receiveMsg.data.to_headimgurl = receiveMsg.data.fromid === uni.getStorageSync('token') ?
						receiveMsg.data.to_headimgurl : receiveMsg.data.from_headimgurl
					receiveMsg.data.message = $utils.generateRichTextNode(receiveMsg.data.message, receiveMsg.data
						.message_type)
					receiveMsg.data.userType = receiveMsg.data.fromid === uni.getStorageSync('token') ?
						'customer' : 'home'
					// this.msgList.push(receiveMsg.data)
					// this.$nextTick(() => {
					//   setTimeout(() => {
					//     this.scrollToBottom()
					//   }, 50)
					// })
					console.log(receiveMsg)
					var pages = getCurrentPages();
					var page = pages[pages.length - 1];
					// #ifdef APP-PLUS
					var currentWebview = page.$getAppWebview();
					if (currentWebview.__uniapp_route === 'pages/live/Audience') {
						uni.showToast({
							title: '您有新的消息，请到消息中心查看',
							duration: 4000,
							icon: 'none'
						})
					}
					// #endif

					uni.vibrateLong({
						success: function() {
							console.log('success')
						}
					})
				}

				if (data.type === 'history') {
					let receiveMsg = data.data.reverse()
					// this.msgList = receiveMsg.map(item => {
					//   item.to_headimgurl = item.fromid === uni.getStorageSync('token') ? item.to_headimgurl : item.from_headimgurl
					//   item.message = $utils.generateRichTextNode(item.message, item.message_type)
					//   item.userType = item.fromid === uni.getStorageSync('token') ? 'customer' : 'home'

					//   return item
					// })

					this.$nextTick().then(() => {
						setTimeout(() => {
							this.scrollToBottom()
						}, 50)
					})
				}
			})


			this.$hideLoading()
			this.pageShow = true
		},

		onUnload() {
			uni.sendSocketMessage({
				data: JSON.stringify({
					type: 'readmsg',
					data: {
						fromid: uni.getStorageSync('token'),
						toid: this.toId,
					}
				})
			})
		},

		onBackPress() {
			uni.sendSocketMessage({
				data: JSON.stringify({
					type: 'readmsg',
					data: {
						fromid: uni.getStorageSync('token'),
						toid: this.toId,
					}
				})
			})
		},

		methods: {
			caozuo() {
				this.opened()
			},

			opened() {
				this.$refs.caozuo.open()
			},
			closed() {
				this.$refs.caozuo.close()
			},
			totousu() {
				uni.navigateTo({
					url: `./jubao?userid=${this.userid}`
				})
			},
			lahei() {
				var that = this
				this.Loop = setTimeout(function() {

					uni.showModal({
						title: '提示',
						content: '是否确定拉黑该用户？',
						success: function(res) {
							if (res.confirm) {
								that.yeslh()
							} else if (res.cancel) {
								console.log('用户点击取消');
							}

						}
					});
				}.bind(this), 100);
			},
			yeslh() {
				console.log(this.msgList)
				this.$http.laback({
					to_uid: this.to_uid,
					is_shield: 0
				}).then(res => {
					console.log(res, "举报")
					if (res.status == 200) {
						uni.showToast({
							title: res.mess
						})
					} else {
						uni.showToast({
							title: res.mess,
							icon: 'none'
						})
					}
				})
			},
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
			sendMsg(data) {
				uni.sendSocketMessage({
					data: JSON.stringify({
						...data
					})
				})

				let receiveMsg = data
				receiveMsg.data.message = $utils.generateRichTextNode(receiveMsg.data.message, receiveMsg.data
					.message_type)
				this.msgList.push(receiveMsg.data)
				setTimeout(() => {
					this.scrollToBottom()
				}, 50)
			},
			getchatlist() {
				if (!this.isMore) {
					uni.stopPullDownRefresh()
					return false
				}
				this.loading = true

				this.$http.getChatMsglist({
					page: this.page,
					toid: this.toId
				}).then(res => {
					console.log(res)
					this.loading = false
					if (res.status === 200) {
						if (res.data.length) {
							let recordList = res.data.reverse()
							let newList = []
							newList = recordList.map(item => {
								item.to_headimgurl = item.fromid === uni.getStorageSync('token') ? item
									.to_headimgurl : item.from_headimgurl
								item.message = $utils.generateRichTextNode(item.message, item.message_type)
								item.userType = item.fromid === uni.getStorageSync('token') ? 'customer' :
									'home'
								// item.from_username = item.from_username
								return item
							})
							this.isGetMore = true
							this.$nextTick().then(() => {
								this.msgList.unshift(...newList)
								this.page = this.page

								uni.stopPullDownRefresh()
								this.$nextTick().then(() => {
									this.isGetMore = false
								})
							})
						} else {
							uni.stopPullDownRefresh()
							this.isMore = false
						}
					} else {
						this.$toast(res.message)
						uni.stopPullDownRefresh()
					}
				}).catch(() => {
					uni.stopPullDownRefresh()
				})
			},
			getMore() {
				if (!this.isMore) {
					uni.stopPullDownRefresh()
					return false
				}
				this.loading = true

				this.$http.getChatMsglist({
					page: this.page + 1,
					toid: this.toId
				}).then(res => {
					console.log(res)
					this.loading = false
					if (res.status === 200) {
						if (res.data.length) {
							let recordList = res.data.reverse()
							let newList = []
							newList = recordList.map(item => {
								item.to_headimgurl = item.fromid === uni.getStorageSync('token') ? item
									.to_headimgurl : item.from_headimgurl
								item.message = $utils.generateRichTextNode(item.message, item.message_type)
								item.userType = item.fromid === uni.getStorageSync('token') ? 'customer' :
									'home'
								return item
							})
							this.isGetMore = true
							this.$nextTick().then(() => {
								this.msgList.unshift(...newList)
								this.page = this.page + 1

								uni.stopPullDownRefresh()
								this.$nextTick().then(() => {
									this.isGetMore = false
								})
							})
						} else {
							uni.stopPullDownRefresh()
							this.isMore = false
						}
					} else {
						console.log(242)
						this.$toast(res.message)
						uni.stopPullDownRefresh()
					}
				}).catch(() => {
					uni.stopPullDownRefresh()
				})
			},

			onShowEmoji(val, emojiStr) {
				if (val) {
					this.showEoji = false
					this.focus = true
				} else {
					uni.hideKeyboard()
					setTimeout(() => {
						this.showEoji = true
						this.focus = false
					}, 300)
				}
			},

			hideKeyboard() {
				this.showEoji = false
				uni.hideKeyboard()
			},

			updataVal(val) {
				this.inputValue = val
			},

			onUpload() {
				this.showEoji = false
				$utils.chooseImg().then(response => {
					this.$loading('上传中')
					uni.uploadFile({
						url: this.$baseUrl + '/api/find/uploadspic',
						filePath: response.tempFilePaths[0],
						name: 'file',
						success: res => {
							const data = JSON.parse(res.data)
							if (data.code === 200) {
								uni.getImageInfo({
									src: response.tempFilePaths[0],
									success: image => {
										let width = 0,
											height = 0
										if (image.width > 400) {
											width = uni.upx2px(400)
											height = uni.upx2px(image.height * (400 / image
												.width))
										} else {
											width = uni.upx2px(image.width)
											height = uni.upx2px(image.height)
										}

										let sendData = {
											type: 'say',
											data: {
												userType: 'customer',
												fromid: uni.getStorageSync('token'),
												toid: this.toUserId,
												message: data.data.src.wz,
												message_type: 'img',
												width: width,
												height: height
											}
										}

										this.$hideLoading()

										this.sendMsg(sendData)
									}
								})
							} else {
								this.$toast(data.msg)
							}
						},

						fail: err => {
							this.$hideLoading()
						}
					})
				})
			},

			getInputMessage(message) {
				this.$http.islahei({
					to_uid: this.userid,
				}).then(res => {
					console.log(res, "是否被拉黑")
					if (res.status == 200) {
						// uni.showToast({
						// 	title:res.mess
						// })
						if (this.islah == true) {
							let sendData = {
								type: 'say',
								data: {
									userType: 'customer',
									fromid: uni.getStorageSync('token'),
									toid: this.toUserId,
									message: message.content,
									message_type: 'text'
								}
							}

							this.sendMsg(sendData)
							this.showEoji = false
							this.inputValue = ''
						} else {
							uni.showToast({
								title: this.hua,
								icon: 'none'
							})
						}
					} else {
						this.islah = false
						this.hua = res.mess
						uni.showToast({
							title: res.mess,
							icon: 'none',
							duration: 4000
						})
					}
				})

			},

			scrollToBottom() {
				uni.pageScrollTo({
					scrollTop: 20000,
					duration: 100
				})
				// const query = uni.createSelectorQuery()
				// query.selectAll('.m-item').boundingClientRect()
				// query.select('#scrollview').boundingClientRect()

				// query.exec(res => {
				// 	this.style.mitemHeight = 0
				// 	res[0].forEach(rect => {
				// 		this.style.mitemHeight = this.style.mitemHeight + rect.height + 20
				// 	})

				// 	if (this.style.mitemHeight > this.style.contentViewHeight) {
				// 		this.scrollTop = this.style.mitemHeight - this.style.contentViewHeight
				// 		uni.pageScrollTo({
				// 			scrollTop: this.scrollTop,
				// 			duration: 0
				// 		})
				// 	}
				// })
			}
		},

		onPullDownRefresh() {
			this.getMore()
		}
	}
</script>

<style lang="scss" scoped>
	.bot {
		// height: 344upx;
		width: 100%;
		background-color: #fff;
		border-top-left-radius: 15px;
		border-top-right-radius: 15px;
		display: flex;
		flex-direction: column;

	}

	.lista {
		width: 100%;
		height: 84upx;
		text-align: center;
		line-height: 84upx;
		padding-bottom: 30upx;
		border-bottom: 2upx solid #F5F5F5;
	}

	.listd {
		width: 100%;
		height: 120upx;
		text-align: center;
		line-height: 120upx;
		padding-bottom: 20upx;
		border-bottom: 2upx solid #F5F5F5;
	}

	.quxiao {
		height: 100upx;
		width: 100%;
		text-align: center;
		line-height: 100upx;
	}

	.header {
		position: fixed;
		background-color: #fff;
		height: 110upx;
		width: 100%;
		top: 0;
		left: 0;
		display: flex;
		z-index: 100;
		align-items: center;
		padding-left: 30upx;
		justify-content: space-between;
	}

	.no-more {
		margin-top: 10upx;
		text-algin: center;
	}

	.tip {
		position: fixed;
		top: 118upx;
		left: 30upx;
		z-index: 100;
		width: 690upx;
		height: 217upx;
		padding: 22upx 30upx 0 30upx;
		background: #fff;
		color: #999;
		font-size: 26upx;

		.tip-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 10upx;

			i {
				color: #999;
				padding-left: 20upx;
			}

			h2 {
				font-size: 34upx;
				color: #333;
			}
		}

		span {
			color: #F23333;
			font-size: 26upx;
			line-height: 1.4;
		}
	}

	.notice {
		display: flex;
		align-items: center;
		position: fixed;
		top: 0;
		width: 100%;
		height: 88upx;
		padding: 0 30upx;
		font-size: 24upx;
		background: #fff;
		color: #999;
		z-index: 100;

		image {
			width: 30upx;
			height: 30upx;
			padding-right: 6upx;
		}
	}

	.gift-btn {
		bottom: 200upx;
	}

	.chat {
		min-height: 100%;
		background: #F4F4F4;

		&>div {
			min-height: 100%;
			height: 100%;
		}

		.active {
			padding-top: 0 !important;
		}

		.content {
			height: auto;
			padding-bottom: 110upx;
			background: #F4F4F4;

		}

		.chat-footer {
			position: fixed;
			width: 100%;
			height: 110upx;
			left: 0upx;
			bottom: 0upx;
		}

		#bottom {
			padding-bottom: 20upx;
		}
	}
</style>
